package util

import (
	"bytes"
	"strconv"
)

func Nagation(a uint8) uint8 {
	return ^a + 1
}

// 计算校验值
func CRC(a []byte) uint8 {

	var sum uint8 = 0
	for i := 0; i < len(a); i++ {
		value := uint8(a[i])
		sum = sum + value
	}

	return Nagation(sum)
}

func BytesToHex(data []byte) string {
	buffer := new(bytes.Buffer)
	for index, b := range data {

		s := strconv.FormatInt(int64(b&0xff), 16)
		if index > 0 {
			buffer.WriteString(" ")
		}
		if len(s) == 1 {
			buffer.WriteString("0x0")
		} else {
			buffer.WriteString("0x")
		}
		buffer.WriteString(s)
	}

	return buffer.String()
}

func ByteToHex(data byte) string {

	s := strconv.FormatInt(int64(data&0xff), 16)
	if len(s) == 1 {
		s = "0x0" + s
	} else {
		s = "0x" + s
	}

	return s
}
